import axios from 'axios'
import { useUserStore } from '@/stores'
import { storeToRefs } from 'pinia'
import router from '@/router'

//创建axios实例
const http = axios.create({
  baseURL: 'https://pcapi-xiaotuxian-front-devtest.itheima.net',
  timeout: 30000
})

//axios请求拦截器
http.interceptors.request.use(
  (config) => {
    const userStore = useUserStore()
    //1. 从Pinia 获取token 数据
    const { userInfo } = storeToRefs(userStore)
    const token = userInfo.value.token
    //2. 按照后端要求拼接token 数据
    if (token) {
      config.headers.Authorization = `Bearer ${token}`
    }
    return config
  },
  (error) => {
    return Promise.reject(error)
  }
)

//axios响应拦截器
http.interceptors.response.use(
  (res) => {
    if (+res.data.code === 1) {
      return res.data
    }
    ElMessage.error(res.data.msg || '服务异常')
    return Promise.reject(res.data)
  },
  (err) => {
    ElMessage.error(err.message || '服务异常')
    if (err.response?.status === 401) {
      router.push('/login')
    }
    return Promise.reject(err)
  }
)

export default http
